<template>
  <view class="refund-page">
    <!-- 商品信息 -->
    <view class="order-info" v-if="orderInfo && orderInfo.id">
      <view class="order-header">
        <text class="order-title">订单信息</text>
        <text class="order-number">订单号：{{ orderInfo.orderNumber }}</text>
      </view>
      <view class="goods-item">
        <image class="goods-image" :src="orderInfo.pic" mode="aspectFill"></image>
        <view class="goods-detail">
          <view class="goods-name">{{ orderInfo.prodName }}</view>
          <view class="goods-spec">{{ orderInfo.remark || '' }}</view>
          <view class="goods-price">
            <text class="price">￥{{ formatPrice(orderInfo.price) }}</text>
            <text class="num">x{{ orderInfo.num }}</text>
          </view>
        </view>
      </view>
      <view class="order-amount">
        <text class="label">实付金额：</text>
        <text class="amount">￥{{ formatPrice(orderInfo.actualTotal) }}</text>
      </view>
    </view>

    <!-- 退款申请表单 -->
    <view class="form-container">
      <u--form ref="formRef" :model="formData" :rules="rules" labelWidth="140">

        <!-- 申请类型 -->
        <u-form-item label="申请类型" prop="applyType" required>
          <u-radio-group v-model="formData.applyType" size="28">
            <u-radio :name="1" label="仅退款" activeColor="#276AEE" icon-size="28"
                     label-size="28"></u-radio>
            <u-radio :name="2" label="退款退货" activeColor="#276AEE" icon-size="28"
                     label-size="28"></u-radio>
          </u-radio-group>
        </u-form-item>

        <!-- 退款金额 -->
        <u-form-item label="退款金额" prop="refundAmount" required>
          <u--input
              v-model="formData.refundAmount"
              type="digit"
              placeholder="请输入退款金额"
              border="none"
              @blur="formatRefundAmount"
          >
          </u--input>
        </u-form-item>

        <!-- 退货数量 -->
        <u-form-item label="退货数量" prop="goodsNum" required>
          <view class="quantity-selector">
            <view class="stepper">
              <view class="btn" :class="{ disabled: formData.goodsNum <= 1 }" @click="decreaseNum">
                -
              </view>
              <input class="num-input" disabled type="number" v-model.number="formData.goodsNum"/>
              <view class="btn" :class="{ disabled: formData.goodsNum >= maxNum }"
                    @click="increaseNum">+
              </view>
            </view>
            <text class="max-tip">最多{{ maxNum }}件</text>
          </view>
        </u-form-item>

        <!-- 申请原因 -->
        <u-form-item label="申请原因" prop="buyerMsg" required>
          <textarea
              v-model="formData.buyerMsg"
              placeholder="请详细说明退款原因，以便商家快速处理"
              maxlength="200"
              autoHeight
          ></textarea>
        </u-form-item>

        <!-- 上传图片 -->
        <u-form-item label="上传凭证" prop="photoFiles">
          <u-upload
              accept="image"
              :fileList="fileListImgs"
              @afterRead="afterRead"
              @delete="deletePic"
              name="Imgs"
              :multiple='true'
              :maxCount="3"
              width="140"
              height="140"
              imageMode="aspectFit"
          >
            <view class="uploadWp">
              <u-icon name="plus" color="#c9cdd4" size="60"></u-icon>
              <text style="color: #c9cdd4;font-size: 24rpx;">点击上传</text>
            </view>
          </u-upload>
          <view class="upload-tip">最多上传3张图片，支持jpg、png格式</view>
        </u-form-item>

      </u--form>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-container">
      <u-button
          type="primary"
          size="large"
          @click="submitRefund"
          :loading="submitting"
          :disabled="submitting"
      >
        {{ submitting ? '提交中...' : '提交申请' }}
      </u-button>
    </view>

  </view>
</template>

<script>

import {
  mapGetters
} from 'vuex'

import baseConfig from '@/config/baseUrl.js'

export default {
  data() {
    const that = this

    return {
      orderId: '',
      orderInfo: {},
      submitting: false,
      formData: {
        applyType: 1, // 申请类型:1,仅退款,2退款退货
        buyerMsg: '', // 申请原因
        goodsNum: 1, // 退货数量
        refundAmount: '', // 退款金额
      },
      fileListImgs: [], // 上传图片列表
      rules: {
        applyType: [{required: true, message: '请选择申请类型'}],
        refundAmount: [
          {required: true, message: '请输入退款金额'},
          {
            validator: (rule, value, callback) => that.validateRefundAmount(rule, value, callback)
          }
        ],
        goodsNum: [
          {required: true, message: '请输入退货数量'}
          // 临时注释掉自定义验证器
          // {validator: this.validateGoodsNum, message: '退货数量不能超过订单数量'}
        ],
        buyerMsg: [
          {required: true, message: '请填写申请原因'},
        ]
      }
    }
  },
  onLoad(opt) {
    this.orderId = opt.id
    this._getOrderDetail(opt.id)
  },
  onReady() {
    // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
    this.$refs.formRef.setRules(this.rules)
  },
  computed: {
    ...mapGetters(['userInfo']),
    maxNum() {
      return parseInt(this.orderInfo.num) || 1
    }
  },
  methods: {
    // 根据id查询订单详情
    _getOrderDetail(id) {
      let params = {id}
      this.$api.getOrderDetail(params).then(res => {
        if (res.success) {
          this.orderInfo = res.result || {}
          // 初始化表单默认值
          this.$set(this.formData, 'goodsNum', parseInt(this.orderInfo.num) || 1)
          this.$set(this.formData, 'refundAmount', String(this.orderInfo.actualTotal || 0))
          console.log('订单详情', this.orderInfo);
        }
      })
    },

    // 格式化价格
    formatPrice(v) {
      const n = Number(v || 0)
      return n.toFixed(2)
    },

    // 增加数量
    increaseNum() {
      const currentNum = parseInt(this.formData.goodsNum) || 1
      if (currentNum < this.maxNum) {
        this.formData.goodsNum = currentNum + 1
      }
    },

    // 减少数量
    decreaseNum() {
      const currentNum = parseInt(this.formData.goodsNum) || 1
      if (currentNum > 1) {
        this.formData.goodsNum = currentNum - 1
      }
    },

    // 验证退款金额
    validateRefundAmount(rule, value, callback) {
      const refundAmount = Number(value)
      const maxAmount = Number(this.orderInfo.actualTotal || 0)
      console.log('退款金额',refundAmount)
      console.log('最大金额',maxAmount)
      console.log('比较',refundAmount > maxAmount)
      if (refundAmount > maxAmount) {
        callback(`不得高于最大退款金额`)
      } else {
        callback()
      }
    },

    // 验证退货数量
    validateGoodsNum(rule, value, callback) {
      // 直接使用 formData 中的值，确保数据一致性
      const goodsNum = parseInt(this.formData.goodsNum) || 1
      const maxNum = parseInt(this.orderInfo.num) || 1

      console.log('验证退货数量:', {
        formDataGoodsNum: this.formData.goodsNum,
        goodsNum,
        maxNum,
        comparison: goodsNum > maxNum,
        orderInfoNum: this.orderInfo.num,
        orderInfo: this.orderInfo
      })

      if (goodsNum > maxNum || goodsNum < 1) {
        callback(false)
      } else {
        callback(true)
      }
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
    },

    // 新增图片
    async afterRead(event) {
      console.log('新增图片', event);
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: event.name,
          url: result,
          fileName: event.file[0].type + event.file[0].size + '',
          filePath: result
        }))
        fileListLen++
      }
    },

    // 上传图片到服务器
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
          filePath: url,
          name: 'file',
          success: (res) => {
            let data = JSON.parse(res.data)
            if (data.success) {
              resolve(data.message)
            }
          }
        });
      })
    },

    // 格式化退款金额
    formatRefundAmount() {
      if (this.formData.refundAmount) {
        const amount = parseFloat(this.formData.refundAmount)
        if (!isNaN(amount)) {
          this.formData.refundAmount = amount.toFixed(2)
        }
      }
    },

    // 提交申请
    async submitRefund() {
      console.log('提交的信息', this.formData)
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        this.submitting = true

        // 处理图片数组
        const photoFilesStr = this.fileListImgs.map(item => item.url).join(',')

        const params = {
          applyType: this.formData.applyType,
          buyerMsg: this.formData.buyerMsg,
          goodsNum: this.formData.goodsNum,
          orderId: this.orderId,
          photoFiles: photoFilesStr,
          refundAmount: Number(this.formData.refundAmount),
          shopCardId: this.orderInfo.shopCardId,
          userId: this.userInfo.id
        }

        const res = await this.$api.addMssdOrderRefund(params)

        if (res.success) {
          uni.showToast({
            title: '申请提交成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '提交失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提交申请失败:', error)
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.refund-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.order-info {
  background: #fff;
  margin-bottom: 20rpx;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 32rpx 20rpx;
    border-bottom: 1rpx solid #f0f2f5;

    .order-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1d2129;
    }

    .order-number {
      font-size: 24rpx;
      color: #86909c;
    }
  }

  .goods-item {
    display: flex;
    padding: 20rpx 32rpx;

    .goods-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      margin-right: 20rpx;
    }

    .goods-detail {
      flex: 1;

      .goods-name {
        font-size: 28rpx;
        color: #1d2129;
        line-height: 1.4;
        margin-bottom: 8rpx;
      }

      .goods-spec {
        font-size: 24rpx;
        color: #86909c;
        margin-bottom: 12rpx;
      }

      .goods-price {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .price {
          font-size: 28rpx;
          color: #ff3131;
          font-weight: 600;
        }

        .num {
          font-size: 24rpx;
          color: #86909c;
        }
      }
    }
  }

  .order-amount {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20rpx 32rpx;
    border-top: 1rpx solid #f0f2f5;

    .label {
      font-size: 28rpx;
      color: #4e5969;
    }

    .amount {
      font-size: 32rpx;
      color: #ff3131;
      font-weight: 600;
      margin-left: 10rpx;
    }
  }
}

.form-container {
  background: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx 0;

  .amount-tip {
    font-size: 24rpx;
    color: #86909c;
    margin-top: 8rpx;
  }

  .quantity-selector {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .stepper {
      display: flex;
      align-items: center;
      border: 1rpx solid #e5e6eb;
      border-radius: 8rpx;
      overflow: hidden;

      .btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f7f8fa;
        color: #1d2129;
        font-size: 32rpx;
        font-weight: 600;

        &.disabled {
          color: #c9cdd4;
          background: #f7f8fa;
        }

        &:active:not(.disabled) {
          background: #e5e6eb;
        }
      }

      .num-input {
        width: 80rpx;
        height: 60rpx;
        text-align: center;
        border: none;
        background: #fff;
        font-size: 28rpx;
        color: #1d2129;
      }
    }

    .max-tip {
      font-size: 24rpx;
      color: #86909c;
    }
  }

  .uploadWp {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 140rpx;
    height: 140rpx;
    background: #f7f8fa;
    border: 2rpx dashed #c9cdd4;
    border-radius: 12rpx;
  }

  .upload-tip {
    font-size: 24rpx;
    color: #86909c;
    margin-top: 12rpx;
  }
}

.submit-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f2f5;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.08);
}

// uView组件样式覆盖
::v-deep .u-form-item {
  padding: 24rpx 32rpx !important;

  .u-form-item__body__left__content__label {
    font-size: 28rpx !important;
    color: #1d2129 !important;
    font-weight: 500 !important;
  }
}

::v-deep .u-radio-group {
  display: flex;
  gap: 40rpx;
}

::v-deep .u-radio {
  margin-right: 0 !important;
}

::v-deep .u-upload__wrap {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}
</style>
